﻿using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using todo.Model;

namespace todo.export
{
    public class PlainTextExporter : IExporter
    {
        private PlainTextExportSettings _settings;

        public ExportSettings Settings
        {
            get { return _settings; }
            set { _settings = (PlainTextExportSettings) value; }
        }

        public PlainTextExporter()
        {
            _settings = new PlainTextExportSettings();
            _settings.IndentCount = 2;
            _settings.IndentType = 0;
        }

        public void Export()
        {
            var frm = new ExportForm();
            frm.Settings = _settings;
            var dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                this.DoExport();
            }
        }

        private void DoExport()
        {
            var dlgSave = new SaveFileDialog();
            dlgSave.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            dlgSave.FileName = Path.GetFileNameWithoutExtension(App.TodoListFile) + ".txt";
            dlgSave.DefaultExt = "txt";
            var dr = dlgSave.ShowDialog();
            if (dr != DialogResult.OK)
            {
                return;
            }
            var fileName = dlgSave.FileName;
            DoExport(fileName);
        }

        private void DoExport(string fileName)
        {
            var todos = App.MainForm.GetTodos();
            var sb = new StringBuilder();
            Output(todos, sb, 0);
            File.WriteAllText(fileName, sb.ToString());
            Process.Start(fileName);
        }

        private void Output(IList<Todo> todos, StringBuilder sb, int level)
        {
            if (todos == null)
            {
                return;
            }
            foreach (var todo in todos)
            {
                Output(todo, sb, level);
            }
        }

        private void Output(Todo todo, StringBuilder sb, int level)
        {
            var done = todo.Checked == 1;
            if (_settings.ExcludeDoneItems && done)
            {
                return;
            }
            var indent = new string(_settings.IndentType == 0 ? ' ' : '\t',
                    level*_settings.IndentCount);
            sb.Append(indent);
            if (_settings.WithCheckmark && done)
            {
                sb.Append('√');
            }
            sb.Append(todo.Title);
            if (!string.IsNullOrEmpty(todo.Description))
            {
                sb.Append('|').Append(todo.Description);
            }
            sb.AppendLine();
            Output(todo.Todos, sb, level + 1);
        }
    }
}